package com.mspbots.rule.queue.producer;

import com.mspbots.api.client.CoreClient;
import com.mspbots.api.service.TenantUserConfigurationService;
import com.mspbots.api.service.TenantUserService;
import com.mspbots.cw.request.TenantUserDTO;
import com.mspbots.cw.request.TenantUsersMappingDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Flux;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author Dinnes
 * @date 2019/10/30
 */
@Slf4j
@Service
public class ManagerProducer {

    @Autowired
    protected CoreClient coreClient;
    @Autowired
    TenantUserService tenantUserService;
    @Autowired
    TenantUserConfigurationService tenantUserConfigurationService;

    @Scheduled(cron = "0 0/1 * * * *")
    public void getUserList() {
        log.info("msg {}", "get Peter's employee");
        Map<String, Object> param = Map.of("teamsUserId", "445d1721-4b02-4441-ba21-249943b1a42f");
        this.coreClient.get("/user-mapping/user", param, TenantUsersMappingDTO.class)
                .flatMap(dto -> this.getUserList(dto.getTenantUserId())
                        .collectList()
                        .map(list -> {
                            List<Long> newList = list.stream().distinct().collect(Collectors.toList());
                            newList.add(dto.getTenantUserId());
                            return newList;
                        }))
                .flatMap(listId -> this.coreClient.get("/tenant/user-configuration/deleteWorkTime", Map.of("userList", listId)))
                .subscribe();
    }

    public Flux<Long> getUserList(long id) {
        return this.coreClient.getFlux("/tenant/user/selectByManagerId/" + id, null, TenantUserDTO.class)
                .switchIfEmpty(Flux.empty())
                .map(TenantUserDTO::getId)
                .expand(this::getUserList);
    }
}
